/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedFaceData } from '@amcax/base';
import { getIdOfPickedObj } from '@app-base/common/utils/render';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';

type pickedDirection = pickedLineData | pickedFaceData;

type FormData = {
  curve1?: pickedLineData;
  curve2?: pickedLineData;
  dir1: pickedDirection;
  dir2: pickedDirection;
  mode: string;
};

type Params = {
  mode: string; // Normal / Direction
  curve1: string;
  curve2: string;
  dir1: string;
  dir2: string;
};

// 混合曲线
function CommandCurveHybrid({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    curve1: null,
    curve2: null,
    mode: 'Normal',
    dir1: null,
    dir2: null,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const { curve1, curve2, mode, dir1, dir2 }: Params = props.params;

    await initEditDependency([curve1, curve2, dir1, dir2]);

    setFormData({
      curve1: picker.generatePickObjByPickID(curve1) as pickedLineData,
      curve2: picker.generatePickObjByPickID(curve2) as pickedLineData,
      mode,
      dir1: dir1
        ? (picker.generatePickObjByPickID(dir1) as pickedDirection)
        : null,
      dir2: dir2
        ? (picker.generatePickObjByPickID(dir2) as pickedDirection)
        : null,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { curve1, curve2, mode, dir1, dir2 } = formData;

    if (curve1 == null || curve2 == null) {
      return false;
    }
    if (mode === 'Direction') {
      if (dir1 == null || dir2 == null) {
        return false;
      }
    }

    return true;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-curve-hybrid', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { curve1, curve2, mode, dir1, dir2 } = formData;

    return confirmCommand(
      {
        type: 'Hybrid',
        a: {
          mode: mode,
          curve1: curve1.edgeId,
          curve2: curve2.edgeId,
          dir1: getIdOfPickedObj(dir1),
          dir2: getIdOfPickedObj(dir2),
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        dir1:
          formData.mode === 'Direction'
            ? {
                type: 'string',
                title: '方向1',
                format: PickInputRJSFFormat.PickDirection,
              }
            : null,
        dir2:
          formData.mode === 'Direction'
            ? {
                type: 'string',
                title: '方向2',
                format: PickInputRJSFFormat.PickDirection,
              }
            : null,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties: {
        mode: {
          title: '模式',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '法向量',
              const: 'Normal',
            },
            {
              type: 'number',
              title: '沿某个方向',
              const: 'Direction',
            },
          ],
          default: 'Normal',
        },
        curve1: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        curve2: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        ...properties,
      },
    };
  }, [formData.mode]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入曲线1',
          'ui:autofocus': props == null,
        },
        curve2: {
          'ui:placeholder': '请输入曲线2',
        },
        dir1: {
          'ui:placeholder': '请输入方向1',
        },
        dir2: {
          'ui:placeholder': '请输入方向2',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveHybrid: CurvedBaseCommand = {
  id: 'CmdCurveHybrid',
  label: 'command.curve-hybrid',
  icon: 'commands/curved/combine-curve',
  create: (label, onClose, props) => (
    <CommandCurveHybrid
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
